package com.web3.management.controller;

import com.web3.management.dto.ApiResponse;
import com.web3.management.dto.request.ChangePasswordRequest;
import com.web3.management.dto.request.LoginRequest;
import com.web3.management.dto.response.LoginResponse;
import com.web3.management.service.AuthService;
import com.web3.management.util.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        LoginResponse response = authService.login(request.getUsername(), request.getPassword());
        return ApiResponse.success("登录成功", response);
    }

    @PostMapping("/logout")
    public ApiResponse<Void> logout() {
        // JWT为无状态认证，登出仅需前端删除Token
        return ApiResponse.success("登出成功", null);
    }

    @GetMapping("/verify")
    public ApiResponse<Map<String, Object>> verify() {
        UserDetails userDetails = authService.getCurrentUser();
        Map<String, Object> data = new HashMap<>();
        data.put("username", userDetails.getUsername());
        return ApiResponse.success("Token有效", data);
    }

    @PostMapping("/refresh")
    public ApiResponse<LoginResponse> refresh(HttpServletRequest request) {
        String token = resolveToken(request);
        LoginResponse response = authService.refreshToken(token);
        return ApiResponse.success("刷新成功", response);
    }

    @PostMapping("/change-password")
    public ApiResponse<Void> changePassword(@Valid @RequestBody ChangePasswordRequest request) {
        // 验证新密码和确认密码是否一致
        if (!request.getNewPassword().equals(request.getConfirmPassword())) {
            return ApiResponse.error(400, "新密码和确认密码不一致");
        }

        authService.changePassword(request.getCurrentPassword(), request.getNewPassword());
        return ApiResponse.success("密码修改成功", null);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return bearerToken;
    }
}
